<?php
/***************************************************************************
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 ***************************************************************************/

if(!defined(IN_PHP))die('Hacking attempt');



//from the www.php.net documentation 
function quote_smart($value)
{
	// Stripslashes
	if (get_magic_quotes_gpc()) {
		$value = stripslashes($value);
	}
	// Quote if not integer
	if (!is_numeric($value)) {
		$value = "'" . mysql_real_escape_string($value) . "'";
	}
	return $value;
}


class INFLobbyDB {
	var $db;
	
	function INFLobbyDB() {
		global $config;
		
		$this->db = mysql_connect($config['serverconfig']['mysqlHost'], $config['serverconfig']['mysqlUser'], $config['serverconfig']['mysqlPassword'])
			or die('Could not connect: ' . mysql_error());
		mysql_select_db($config['serverconfig']['mysqlDatabase']) or die('Could not select database');
	}
	
	/*
	 * @return returns the challengeid from the database query
	 */
	function saveChallenge($challengeReply, $IP, $time) {
		$query = 'INSERT INTO infl_challenges SET `reply`='.quote_smart($challengeReply).', `IP`='.quote_smart($IP).', `time`='.quote_smart($time);
		$result = mysql_query($query) or die('Query failed: \''.$query.'\'' . mysql_error());
		
		return mysql_insert_id();
	}
	
	function cleanupChallenges() {
		global $config;
		
		$query = 'DELETE FROM infl_challenges WHERE `time`<'.quote_smart(time()-$config['serverconfig']['challengeLifeTime']);
		$result = mysql_query($query) or die('Query failed: \''.$query.'\'' . mysql_error());
	}
	
	function getChallenge($id) {
		global $config;
		
		$query = 'SELECT * FROM infl_challenges WHERE `challengeid`='.quote_smart($id).' AND `time`>='.(time()-$config['serverconfig']['challengeLifeTime']);
		$result = mysql_query($query) or die('Query failed: \''.$query.'\'' . mysql_error());
		
		return mysql_fetch_assoc($result);
	}
	
	function deleteChallenge($id) {
		if(is_numeric($id)) {
			$query = 'DELETE FROM infl_challenges WHERE `challengeid`='.quote_smart($id);
			$result = mysql_query($query) or die('Query failed: \''.$query.'\'' . mysql_error());
			return true;
		}
		return false;
	}
	
	//TODO improve SQL statement
	function cleanupSessions() {
		global $config;
		
		//extend required polling intervall for users which are not waiting or uninitialized
		$query = 'SELECT `userid` FROM infl_users WHERE (`status`=0 AND `lastpoll`<'.quote_smart(time()-$config['serverconfig']['sessionLifeTime']).') OR `lastpoll`<'.quote_smart(time()-$config['serverconfig']['sessionLifeTime']*10);
		$result = mysql_query($query) or die('Query failed: \''.$query.'\' ' . mysql_error());
		while($row = mysql_fetch_assoc($result)) {
			$userlist .= '`userid`='.$row['userid'].' OR ';
		}
		$userlist = substr($userlist, 0, -4);
		
		if($userlist) {
			$query = 'DELETE FROM infl_users WHERE '.$userlist;
			$result = mysql_query($query) or die('Query failed: \''.$query.'\'' . mysql_error());
		
			$query = 'DELETE FROM infl_queueinfo WHERE '.$userlist;
			$result = mysql_query($query) or die('Query failed: \''.$query.'\'' . mysql_error());		
		}
	}
	
	function saveSession($idGeneratorCallback) {
		do {
			$sessionid = $idGeneratorCallback();
			$query = 'INSERT INTO infl_users SET `sessionid`='.quote_smart($sessionid).', `ip`='.quote_smart($_SERVER['REMOTE_ADDR']).', `lastpoll`='.quote_smart(time());
			$result = mysql_query($query);
			//$userid = mysql_insert_id();

			//not a duplicate key
			if(mysql_errno() && mysql_errno()!=1062) {
				die('Query failed: ' . mysql_error());
			}
		} while(!$result);
		
		return $sessionid;
	}
	
	/*
	 * update nickname, but only if sessionid and ip match
	 *
	 * @return true on success, otherwise false
	 */
	function setNickname($sessionId, $nickname) {
		$query = 'UPDATE `infl_users` SET `nick`='.quote_smart($nickname).', `lastpoll`='.
			quote_smart(time()).' WHERE `sessionid`='.quote_smart($sessionId).' AND '.'`ip`='.quote_smart($_SERVER['REMOTE_ADDR']);
			
		$result = mysql_query($query);
		
		return $result && mysql_affected_rows() ? true : false;
	}
	
	function getUserId($sessionId) {
		$query = 'SELECT `userid` FROM infl_users WHERE `sessionid`='.quote_smart($sessionId).' AND '.'`ip`='.quote_smart($_SERVER['REMOTE_ADDR']);
		$result = mysql_query($query);
		
		if($result) {
			$row = mysql_fetch_assoc($result);
			return $row['userid'] ? $row['userid'] : 0;
		}
		
		return 0;
	}
	
	function getQueueInfo() {
		$query = 'SELECT * FROM infl_queueinfo';
		$result = mysql_query($query) or die('Query failed: \''.$query.'\'' . mysql_error());
			
			
		while($row = mysql_fetch_assoc($result)) {
			$userlist[intval($row['queueid'])][] = intval($row['userid']);
		}
			
		return $userlist;
	}
	
	function setQueueInfo($userid, $queues) {
		if(!is_array($queues))return false;
		
		$query = 'DELETE FROM infl_queueinfo WHERE `userid`='.quote_smart($userid);
		$result = mysql_query($query) or die('Query failed: \''.$query.'\' ' . mysql_error());
		
		foreach($queues as $v) {
			$query = 'INSERT INTO infl_queueinfo SET `userid`='.quote_smart($userid).', `queueid`='.quote_smart($v);
			$result = mysql_query($query) or die('Query failed: \''.$query.'\' ' . mysql_error());
		}
		
		return true;
	}
	
	/*
	 * update status, but only if sessionid and ip match
	 *
	 * @return true on success, otherwise false
	 */
	function setStatus($sessionId, $status) {
		$query = 'UPDATE infl_users SET `status`='.quote_smart($status).', `lastpoll`='.
			quote_smart(time()).' WHERE `sessionid`='.quote_smart($sessionId); //.' AND '.'`ip`='.quote_smart($_SERVER['REMOTE_ADDR']);
		
		$result = mysql_query($query) or die('Query failed: \''.$query.'\' ' . mysql_error());;
		
		return $result && mysql_affected_rows() ? true : false;
	}
	
	/*
	 * update lastpoll, but only if sessionid and ip match
	 *
	 * @return true on success, otherwise false
	 */
	function updateLastpoll($userId) {
		$query = 'UPDATE infl_users SET `lastpoll`='.quote_smart(time()).' WHERE `userid`='.quote_smart($userId);
			
		$result = mysql_query($query);
		
		return $result && mysql_affected_rows() ? true : false;
	}
	
	function getUserInfo() {
		$query = 'SELECT `userid`,`nick`,`status` FROM infl_users';
		$result = mysql_query($query) or die('Query failed: \''.$query.'\' ' . mysql_error());
		
		$out = array();
		while($row = mysql_fetch_assoc($result)) {
			$row['userid'] = intval($row['userid']);
			$row['status'] = intval($row['status']);
			
			$out[] = $row;
		}
		
		return $out;
	}
}
?>